<template lang="pug">
  .content(v-loading="loading")
    el-card.pr.detail.commonCard(shadow="never")
      h2 心理行为评测({{info.month}}个月宝宝)
      p
        span 姓名：{{info.childrenName}}
        span 性别：{{dictFilter(info.gender, 'sex')}}
        span 出生年月：{{info.birthday | dateFilter}}
      p 评测时间：{{info.evaluatingDate | dateFilter}}
      .extra
        el-button.export(type="success" size="small" @click="exportHandle") 导出
    el-card.commonCard(shadow="never")
      h2(slot="header") 身高体重曲线
      bmi-view(
        v-if="info.bmi"
        :bmi="info.bmi"
        :name="info.childrenName"
        :gender="info.gender"
        :height="info.height"
        :weight="info.weight"
      )
    el-card.commonCard(shadow="never")
      h2(slot="header") 评测报告
      p.reportResult
        span 宝宝智龄：{{scoreIt}}
        span 发育商DQ：{{scoreDev}}
        span(:style="{color: resultObj.color}") {{resultObj.str}}
      table(class="scoreTable" cellspacing="0" cellpadding="0")
        tr
          th 测试领域
          th(v-for="item in dimensionScores" :key="item.id") {{item.dimensionName}}
        tr
          td 发育商
          td(v-for="item in dimensionScores" :key="item.id") {{item.score_dev.toFixed(1)}}
        tr
          td 发育商
          td(v-for="item in dimensionScores" :key="item.id") {{item.score_it.toFixed(1)}}
      alert(type="warning") 交流互动警示行为评分低于7分视为正常，7-11分随访，12-30分存在交流互动障碍危险，大于30分高度疑似ASD
      #echartsBox(style="height: 480px")
    el-card.commonCard(shadow="never")
      h2(slot="header") 总体评估建议
      p {{totalAdvise}}
      section.adviseItem(v-for="item in failedQuestions" :key="item.id")
        h3
          span {{item.title}}
        p {{item.advise}}
    el-card.commonCard(shadow="never")
      h2(slot="header") 评估建议
      assess-high-level(:highLevelInfo="info.highLevelInfo")
    el-card.commonCard(shadow="never")
      h2(slot="header") 测评题目
      answer-sheet(:answerSheet="info.answerSheet")
</template>
<script>
import Alert from '@/components/Basic/Alert'
import echartsMixin from '@/components/Basic/Charts/mixins/resize'
import dictMixin from '@/mixins/dict'
import { psychologicalBehavior, exportPdf } from './api'
import AssessHighLevel from './components/assessHighLevel'
import AnswerSheet from './components/answerSheet'
import BmiView from './components/bmiView'

const communicationId = '2c92848567977b50016797a129d909b4'

const barColors = ['#e0366e', '#ffba00', '#4477a3', '#6eacfa', '#5acab9', '#f0f0f0']

function getResult (value) {
  let color = ''
  let str = ''
  if (value < 70) {
    color = barColors[0]
    str = '偏低'
  } else if (value < 85) {
    color = barColors[1]
    str = '落后'
  } else if (value < 115) {
    color = barColors[2]
    str = '正常'
  } else if (value < 130) {
    color = barColors[3]
    str = '优秀'
  } else {
    color = barColors[4]
    str = '超常'
  }
  return { color, str }
}

export default {
  components: {
    Alert,
    AssessHighLevel,
    AnswerSheet,
    BmiView
  },
  mixins: [echartsMixin, dictMixin],
  data () {
    return {
      loading: false,
      info: {},
      dimensionScores: [],
      failedQuestions: [],
      echartsId: 'echartsBox'
    }
  },
  computed: {
    id () {
      return this.$route.query.id
    },
    // 智力分
    scoreIt () {
      const { dimensionScores } = this
      return dimensionScores.reduce((prev, cur) => {
        return prev + (cur.dimensionId !== communicationId ? (cur?.score_it || 0) : 0)
      }, 0) / (dimensionScores.length - 1)
    },
    // 育智商值/指数
    scoreDev () {
      const { dimensionScores } = this
      return dimensionScores.reduce((prev, cur) => {
        return prev + (cur.dimensionId !== communicationId ? cur.score_dev : 0)
      }, 0) / (dimensionScores.length - 1)
    },
    resultObj () {
      const { scoreDev } = this
      return getResult(scoreDev.toFixed(2))
    },
    // 总体评估建议
    totalAdvise () {
      const { dimensionScores, scoreDev } = this
      const communication = dimensionScores.find(x => x.dimensionId === communicationId)
      if (communication) {
        if (communication.score_it > 12 && communication.score_it <= 30) {
          return '您的宝宝存在一定的交流互动障碍，家长请尽早咨询专业机构。'
        }
        if (communication.score_it > 30) {
          return '您的宝宝有较严重的交流互动障碍或自闭倾向，家长请尽快咨询专业机构确认并尽早干预。'
        }
      }
      if (scoreDev < 70) {
        return '您的宝宝心理行为发育较同龄宝宝偏低，请您咨询老师提供相关提升方案。'
      }
      if (scoreDev > 69 && scoreDev < 85) {
        return '您的宝宝心理行为发育较同龄宝宝偏低，请您咨询老师提供相关提升方案。'
      }
      return '您的宝宝心理行为发育良好，请继续保持。'
    }
  },
  watch: {
    id: {
      handler (val) {
        this.getData(val)
      },
      immediate: true
    }
  },
  methods: {
    // 获取详情数据
    getData (evaluateRecordId) {
      this.loading = true
      psychologicalBehavior({ evaluateRecordId }).then(res => {
        const { dimensionScores, failedQuestions, ...rest } = res || {}
        console.log(rest)
        this.dimensionScores = (dimensionScores || []).map(x => {
          x.score_it = parseFloat(x.score / 10)
          x.score_dev = parseFloat((x.score / res.month) * 10)
          return x
        })
        console.log(this.dimensionScores)
        this.failedQuestions = failedQuestions || []
        this.info = rest
        this.getEcharts(this.dimensionScores)
      }).finally(() => {
        this.loading = false
      })
    },
    // 导出
    exportHandle () {
      exportPdf(this.id).then(data => {
        top.location.href = data
      })
    },
    getEcharts (values) {
      const { scoreDev } = this
      const label = []
      const devArr = []
      values.forEach(x => {
        if (x.dimensionId !== communicationId) {
          label.push(x.dimensionName)
          devArr.push({
            value: parseFloat(x.score_dev.toFixed(1)),
            itemStyle: {
              color: getResult(x.score_dev).color
            },
            label: {
              show: true,
              position: 'inside'
            }
          })
        }
      })
      label.push('综合评价')
      devArr.push({
        value: parseFloat(scoreDev.toFixed(1)),
        itemStyle: {
          color: getResult(scoreDev).color
        },
        label: {
          show: true,
          position: 'inside'
        }
      })
      const options = {
        color: barColors,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: params => {
            const param = params[params.length - 1]
            return '<h4 style="color:#fff">' + param.name + '</h4>' + param.marker + '<span>本次测评：' + param.data.value + '分（' + getResult(param.data.value).str + '）</span>'
          }
        },
        legend: {
          top: 48,
          data: ['偏低(69分以下)', '落后(70-84分)', '正常(85-114分)', '优秀(115-129分)', '超常(130分以上)', '本次测评']
        },
        grid: {
          top: 110,
          left: '6%',
          right: '12%',
          bottom: 0,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: label,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          name: '发育商',
          nameLocation: 'middle',
          axisLabel: {
            show: false
          },
          type: 'value'
        },
        series: [
          {
            name: '偏低(69分以下)',
            type: 'line',
            barWidth: 30,
            data: new Array(label.length).fill(50),
            itemStyle: {
              opacity: 0
            },
            lineStyle: {
              width: 0
            },
            markLine: {
              data: [
                { type: 'min', name: '平均值', label: { formatter: '偏低(0-69分)' }}
              ]
            }
          },
          {
            name: '落后(70-84分)',
            type: 'line',
            data: new Array(label.length).fill(70),
            itemStyle: {
              opacity: 0
            },
            lineStyle: {
              width: 0
            },
            markLine: {
              data: [
                { type: 'min', name: '平均值', label: { formatter: '落后(70-84分)' }}
              ]
            }
          },
          {
            name: '正常(85-114分)',
            type: 'line',
            data: new Array(label.length).fill(85),
            itemStyle: {
              opacity: 0
            },
            lineStyle: {
              width: 0
            },
            markLine: {
              data: [
                { type: 'min', name: '平均值', label: { formatter: '正常(85-114分)' }}
              ]
            }
          },
          {
            name: '优秀(115-129分)',
            type: 'line',
            data: new Array(label.length).fill(115),
            itemStyle: {
              opacity: 0
            },
            lineStyle: {
              width: 0
            },
            markLine: {
              data: [
                { type: 'min', name: '平均值', label: { formatter: '优秀(115-129分)' }}
              ]
            }
          },
          {
            name: '超常(130分以上)',
            type: 'line',
            data: new Array(label.length).fill(130),
            itemStyle: {
              opacity: 0
            },
            lineStyle: {
              width: 0
            },
            markLine: {
              data: [
                { type: 'min', name: '平均值', label: { formatter: '超常(130分以上)' }}
              ]
            }
          },
          {
            name: '本次测评',
            type: 'bar',
            zlevel: 6,
            barWidth: 30,
            data: devArr
          }
        ]
      }
      this.$_chartMixin_init(options)
    }
  }
}
</script>
<style lang="scss" scoped>
.detail{
  h2 {
    margin-bottom: 12px;
  }

  p {
    margin-top: 5px;

    > span {
      margin-right: 20px
    }
  }

  .extra{
    position: absolute;
    right: 16px;
    top: 16px
  }
}

.reportResult {

  > span {
    margin-right: 24px;
  }
}

.scoreTable{
    width:100%;
    border-radius: 10px;
    overflow: hidden;
    margin: 24px auto;

    th {
      background: #807fc3;
      font-size: 14px;
      color:#fff;
      text-align: center;
      padding:10px 0;
      border: 1px solid #fff;
    }

    td {
      background: #e4e3fd;
      font-size: 14px;
      color:#50576a;
      text-align: center;
      padding:10px 0;
      border: 1px solid #fff;
    }
}

.adviseItem{
  h3 {
    span {
      display: inline-block;
      background: $green;
      color: #fff;
      font-weight: normal;
      padding: 4px 24px 4px 12px;
      font-size: 14px;
      border-top-right-radius: 12px;
      border-bottom-right-radius: 12px;
    }
  }
}
</style>
